package com.hanson.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.common.bean.GoodsRuleItemBean;
import com.hanson.common.bean.SearchBean;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.*;
import com.hanson.mapper.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import java.util.*;

@Service
public class GoodsService {
    @Autowired
    private GoodsBeanMapper goodsBeanMapper;
    @Autowired
    private GoodsTypeBeanMapper goodsTypeBeanMapper;
    @Autowired
    private GoodsTypeMappingBeanMapper goodsTypeMappingBeanMapper;
    @Autowired
    private GoodsAttrBeanMapper goodsAttrBeanMapper;
    @Autowired
    private GoodsAttrValueBeanMapper goodsAttrValueBeanMapper;
    @Autowired
    private GoodsContentBeanMapper goodsContentBeanMapper;
    @Autowired
    private GoodsCollectBeanMapper goodsCollectBeanMapper;
    @Autowired
    private UserBeanMapper userBeanMapper;


    /**
     * 新增商品
     *
     * @param goodsBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void addGoods(GoodsBean goodsBean, Integer merId) {
        /**基本属性**/
        goodsBean.setCreateDate(new Date());
        goodsBean.setPrice(BusinessUtil.getDbAmount(goodsBean.getWebPrice()));
        goodsBean.setVipPrice(BusinessUtil.getDbAmount(goodsBean.getWebVipPrice()));
        goodsBean.setOldPrice(BusinessUtil.getDbAmount(goodsBean.getWebOldPrice()));
        goodsBean.setSpreadMoney(BusinessUtil.getDbAmount(goodsBean.getWebSpreadMoney()));
        goodsBean.setSpreadChildMoney(BusinessUtil.getDbAmount(goodsBean.getWebSpreadChildMoney()));
        goodsBean.setMerId(merId);
        if (CollectionUtils.isNotEmpty(goodsBean.getSliderImages())) {
            goodsBean.setSliderImage(String.join(",", goodsBean.getSliderImages()));
        }
        goodsBeanMapper.insert(goodsBean);
        addCommon(goodsBean);
    }

    /**
     * 修改商品
     *
     * @param goodsBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateGoods(GoodsBean goodsBean) {
        GoodsBean returnBean = goodsBeanMapper.selectByPrimaryKey(goodsBean.getId());
        if (null != returnBean) {
            goodsBean.setCreateDate(returnBean.getCreateDate());
            goodsBean.setPrice(BusinessUtil.getDbAmount(goodsBean.getWebPrice()));
            goodsBean.setVipPrice(BusinessUtil.getDbAmount(goodsBean.getWebVipPrice()));
            goodsBean.setOldPrice(BusinessUtil.getDbAmount(goodsBean.getWebOldPrice()));
            goodsBean.setSpreadMoney(BusinessUtil.getDbAmount(goodsBean.getWebSpreadMoney()));
            goodsBean.setSpreadChildMoney(BusinessUtil.getDbAmount(goodsBean.getWebSpreadChildMoney()));

            if (CollectionUtils.isNotEmpty(goodsBean.getSliderImages())) {
                goodsBean.setSliderImage(String.join(",", goodsBean.getSliderImages()));
            }
            goodsBeanMapper.updateByPrimaryKey(goodsBean);
            deleteCommon(goodsBean.getId());
            addCommon(goodsBean);
        }
    }

    /**
     * 详情 把依赖查询出来
     *
     * @param id
     * @return
     */
    public GoodsBean detail(Integer id) {
        GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(id);
        if (null != goodsBean) {
            if (StringUtils.isNotEmpty(goodsBean.getSliderImage())) {
                goodsBean.setSliderImages(Arrays.asList(goodsBean.getSliderImage().split(",")));
            }
            List<GoodsContentBean> goodsContentBeans = goodsContentBeanMapper.selectByGoodsId(id);
            if (CollectionUtils.isNotEmpty(goodsContentBeans)) {
                goodsBean.setContent(goodsContentBeans.get(0).getContent());
            }
            List<GoodsTypeMappingBean> goodsTypeMappingBeanList = goodsTypeMappingBeanMapper.selectByGoodsId(id);
            if (CollectionUtils.isNotEmpty(goodsTypeMappingBeanList)) {
                List<String> typeIds = new ArrayList<>();
                goodsTypeMappingBeanList.stream().forEach(c -> {
                    typeIds.add(String.valueOf(c.getTypeId()));
                });
                goodsBean.setTypeIds(typeIds);
            }
            List<GoodsAttrBean> goodsAttrBeanList = goodsAttrBeanMapper.selectByGoodsId(id);
            if (CollectionUtils.isNotEmpty(goodsAttrBeanList)) {
                List<GoodsRuleItemBean> items = new ArrayList<>();
                goodsAttrBeanList.stream().forEach(c -> {
                    GoodsRuleItemBean goodsRuleItemBean = new GoodsRuleItemBean();
                    goodsRuleItemBean.setValue(c.getAttrName());
                    goodsRuleItemBean.setDetail(Arrays.asList(c.getAttrValues().split(",")));
                    goodsRuleItemBean.setDetailValue("");
                    items.add(goodsRuleItemBean);
                });
                goodsBean.setItems(items);
            }
            List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsId(id);
            if (CollectionUtils.isNotEmpty(goodsAttrValueBeanList)) {
                //单规格
                if (goodsBean.getSpecType().equals("0")) {
                    goodsBean.setAttr(JSONObject.parseObject(goodsAttrValueBeanList.get(0).getDetail(), GoodsAttrValueBean.class));
                    goodsBean.setAttrs(new ArrayList<>());
                } else {
                    List<JSONObject> attrs = new ArrayList<>();
                    goodsAttrValueBeanList.stream().forEach(c -> {
                        JSONObject jsonObject = (JSONObject) JSONObject.parse(c.getDetail());
                        jsonObject.put("suk", c.getSuk());
                        attrs.add(jsonObject);
                    });
                    goodsBean.setAttrs(attrs);
                    goodsBean.setAttr(new GoodsAttrValueBean());
                }
            }
            goodsBean.setWebPrice(BusinessUtil.getWebAmount(goodsBean.getPrice()));
            goodsBean.setWebVipPrice(BusinessUtil.getWebAmount(goodsBean.getVipPrice()));
            goodsBean.setWebOldPrice(BusinessUtil.getWebAmount(goodsBean.getOldPrice()));
            goodsBean.setWebSpreadMoney(BusinessUtil.getWebAmount(goodsBean.getSpreadMoney()));
            goodsBean.setWebSpreadChildMoney(BusinessUtil.getWebAmount(goodsBean.getSpreadChildMoney()));
        }
        return goodsBean;
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(id);
        if (null != goodsBean) {
            goodsBeanMapper.deleteByPrimaryKey(id);
            goodsCollectBeanMapper.deleteByGoodsId(id);
            deleteCommon(id);
        }
    }

    public void setSort(int sort, int id) {
        goodsBeanMapper.updateSortById(sort, id);
    }

    public void setIsShow(int isShow, int id) {
        goodsBeanMapper.updateIsShowById(isShow, id);
    }

    public Page<GoodsBean> listGoods(Page<GoodsBean> page, GoodsBean goodsBean) {
        List<GoodsBean> list = goodsBeanMapper.listGoods(page, goodsBean);
        if (CollectionUtils.isNotEmpty(list)) {
            for (GoodsBean c : list) {
                List<GoodsTypeMappingBean> goodsTypeMappingBeanList = goodsTypeMappingBeanMapper.selectByGoodsId(c.getId());
                if (CollectionUtils.isNotEmpty(goodsTypeMappingBeanList)) {
                    StringBuffer typeBuffer = new StringBuffer();
                    for (GoodsTypeMappingBean goodsTypeMappingBean : goodsTypeMappingBeanList) {
                        GoodsTypeBean goodsTypeBean = goodsTypeBeanMapper.selectByPrimaryKey(goodsTypeMappingBean.getTypeId());
                        if (null != goodsTypeBean) {
                            typeBuffer.append(goodsTypeBean.getCateName()).append(",");
                        }
                    }
                    c.setTypeNames(typeBuffer.length() > 0 ? typeBuffer.substring(0, typeBuffer.length() - 1).toString() : "");
                    c.setWebPrice(BusinessUtil.getWebAmount(c.getPrice()));
                    c.setWebVipPrice(BusinessUtil.getWebAmount(c.getVipPrice()));
                    c.setWebOldPrice(BusinessUtil.getWebAmount(c.getOldPrice()));
                    c.setWebSpreadMoney(BusinessUtil.getWebAmount(c.getSpreadMoney()));
                }
                UserBean userBean = userBeanMapper.selectByPrimaryKey(c.getMerId());
                if(null != userBean){
                    c.setMerName(userBean.getUserName());
                }
            }
        }
        return page.setRecords(list);
    }

    /**
     * 获取商品简要数据 首页展示用
     *
     * @return
     */
    public List<GoodsBean> getSimpleGoodsList(int page, int limit, SearchBean searchBean,ModelMap modelMap) {
        List<GoodsTypeMappingBean> goodsIdList = getGoodsIdsByType(searchBean.getTypeId(),modelMap);
        searchBean.setGoodsIdList(goodsIdList);
        Page<GoodsBean> pageInfo = new Page<>(page, limit);
        List<GoodsBean> list = goodsBeanMapper.listSimpleGoods(pageInfo, searchBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                c.setWebPrice(BusinessUtil.getWebAmount(c.getPrice()));
                c.setWebVipPrice(BusinessUtil.getWebAmount(c.getVipPrice()));
                c.setWebOldPrice(BusinessUtil.getWebAmount(c.getOldPrice()));
            });
        }
        return list;
    }

    /**
     * 获取所有分类商品
     *
     * @return
     */
    public List<GoodsBean> getSimpleGoodsByType(Integer typeId,ModelMap modelMap) {
        List<GoodsTypeMappingBean> goodsIdList = getGoodsIdsByType(typeId,modelMap);
        List<GoodsBean> goodsBeanList = null;
        if (CollectionUtils.isNotEmpty(goodsIdList)) {

            goodsBeanList = goodsBeanMapper.listSimpleGoodsByIds(goodsIdList);
            if (CollectionUtils.isNotEmpty(goodsBeanList)) {
                goodsBeanList.stream().forEach(c -> {
                    c.setWebPrice(BusinessUtil.getWebAmount(c.getPrice()));
                    c.setWebVipPrice(BusinessUtil.getWebAmount(c.getVipPrice()));
                    c.setWebOldPrice(BusinessUtil.getWebAmount(c.getOldPrice()));
                });
            }
        }
        return goodsBeanList;
    }

    private List<GoodsTypeMappingBean> getGoodsIdsByType(Integer typeId,ModelMap modelMap) {
        List<GoodsTypeMappingBean> goodsIdList = new ArrayList<>();
        if(null == typeId || typeId == 0){
            modelMap.put("typeId",0);
            modelMap.put("typeName","默认");
            return goodsIdList;
        }
        GoodsTypeBean goodsTypeBean = goodsTypeBeanMapper.selectByPrimaryKey(typeId);
        if (null != goodsTypeBean) {
            modelMap.put("typeId",typeId);
            modelMap.put("typeName",goodsTypeBean.getCateName());
            //一级分类
            if (goodsTypeBean.getPid() == 0) {
                List<GoodsTypeBean> goodsTypeBeanList = goodsTypeBeanMapper.selectByPid(goodsTypeBean.getId());
                if (CollectionUtils.isNotEmpty(goodsTypeBeanList)) {
                    for (GoodsTypeBean c : goodsTypeBeanList) {
                        List<GoodsTypeMappingBean> tempList = goodsTypeMappingBeanMapper.selectByTypeId(c.getId());
                        if (CollectionUtils.isNotEmpty(tempList)) {
                            goodsIdList.addAll(tempList);
                        }
                    }
                }
            } else {
                goodsIdList = goodsTypeMappingBeanMapper.selectByTypeId(typeId);
            }
        }else{
            modelMap.put("typeId",0);
            modelMap.put("typeName","默认");
        }
        return goodsIdList;
    }

    public List<GoodsBean> getRecommendGoods() {
        List<GoodsBean> goodsBeanList = goodsBeanMapper.listRecommendGoods();
        if (CollectionUtils.isNotEmpty(goodsBeanList)) {
            goodsBeanList.stream().forEach(c -> {
                c.setWebPrice(BusinessUtil.getWebAmount(c.getPrice()));
                c.setWebVipPrice(BusinessUtil.getWebAmount(c.getVipPrice()));
                c.setWebOldPrice(BusinessUtil.getWebAmount(c.getOldPrice()));
            });
        }
        return goodsBeanList;
    }

    /**
     * 删除商品依赖
     *
     * @param goodsId
     */
    private void deleteCommon(Integer goodsId) {
        goodsTypeMappingBeanMapper.deleteByGoodsId(goodsId);
        goodsAttrBeanMapper.deleteByGoodsId(goodsId);
        goodsAttrValueBeanMapper.deleteByGoodsId(goodsId);
        goodsContentBeanMapper.deleteByGoodsId(goodsId);
    }

    private void addCommon(GoodsBean goodsBean) {
        final int[] stock = {0};
        /**商品类型**/
        if (CollectionUtils.isNotEmpty(goodsBean.getTypeIds())) {
            goodsBean.getTypeIds().stream().forEach(c -> {
                GoodsTypeMappingBean goodsTypeMappingBean = new GoodsTypeMappingBean();
                goodsTypeMappingBean.setCreateDate(new Date());
                goodsTypeMappingBean.setGoodsId(goodsBean.getId());
                goodsTypeMappingBean.setTypeId(Integer.parseInt(c));
                goodsTypeMappingBeanMapper.insert(goodsTypeMappingBean);
            });
        }
        /**商品属性富文本**/
        if (StringUtils.isNotEmpty(goodsBean.getContent())) {
            GoodsContentBean goodsContentBean = new GoodsContentBean();
            goodsContentBean.setChangeTime(new Date());
            goodsContentBean.setGoodsId(goodsBean.getId());
            goodsContentBean.setContent(goodsBean.getContent());
            goodsContentBeanMapper.insert(goodsContentBean);
        }

        /***商品规格 但规格的为空*/
        if (CollectionUtils.isNotEmpty(goodsBean.getItems())) {
            goodsBean.getItems().stream().forEach(c -> {
                GoodsAttrBean goodsAttrBean = new GoodsAttrBean();
                goodsAttrBean.setGoodsId(goodsBean.getId());
                goodsAttrBean.setAttrName(c.getValue());
                goodsAttrBean.setAttrValues(String.join(",", c.getDetail()));
                goodsAttrBeanMapper.insert(goodsAttrBean);
            });
        }

        /**商品规格组合结果**/
        if (CollectionUtils.isNotEmpty(goodsBean.getAttrs())) {
            for (JSONObject c : goodsBean.getAttrs()) {
                GoodsAttrValueBean goodsAttrValueBean = new GoodsAttrValueBean();
                if (c.containsKey("detail")) {
                    JSONObject detailJson = c.getJSONObject("detail");
                    StringBuffer sukSb = new StringBuffer();
                    for (Map.Entry<String, Object> entry : detailJson.entrySet()) {
                        sukSb.append(entry.getValue()).append(",");
                    }
                    goodsAttrValueBean.setSuk(sukSb.substring(0, sukSb.length() - 1).toString());
                }
                goodsAttrValueBean.setDetail(JSON.toJSONString(c));
                goodsAttrValueBean.setGoodsId(goodsBean.getId());
                goodsAttrValueBean.setStock(c.getInteger("stock"));
                goodsAttrValueBean.setVipPrice(BusinessUtil.getDbAmount(c.getString("vipPrice")) + "");
                goodsAttrValueBean.setPrice(BusinessUtil.getDbAmount(c.getString("price")) + "");
                goodsAttrValueBean.setOldPrice(BusinessUtil.getDbAmount(c.getString("oldPrice")) + "");
                goodsAttrValueBean.setImage(c.getString("image"));
                goodsAttrValueBeanMapper.insert(goodsAttrValueBean);
                stock[0] += c.getInteger("stock");
            }
            goodsBean.setStock(stock[0]);
            goodsBeanMapper.updateByPrimaryKey(goodsBean);
        }
    }

    public int statisAlarmGoods() {
        return goodsBeanMapper.countAlarmGoods();
    }

    public GoodsBean selectById(String id) {
        return goodsBeanMapper.selectByPrimaryKey(Integer.parseInt(id));
    }
}
